package com.hui.demo.security;

import com.hui.demo.error.BussinessException;
import com.hui.demo.model.User;
import com.hui.demo.model.UserRoleRel;
import com.hui.demo.service.RoleService;
import com.hui.demo.service.UserRoleRelService;
import com.hui.demo.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义用户服务类
 * @author ziv
 * @date 2019-01-07
 */
@Service
public class CustomUserService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private UserRoleRelService userRoleRelService;

    @Resource
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        List<User> userList = userService.findByUserName(userName);
        if(userList.size() == 0) {
            throw new BussinessException("用户不存在");
        }
        org.springframework.security.core.userdetails.User userdetails = null;
        for (User user : userList) {
            List<UserRoleRel> userRoleRelList = userRoleRelService.findByUserId(user.getUserID());
            List<GrantedAuthority> authorityList = new ArrayList<>();
            if (userRoleRelList != null && userRoleRelList.size() > 0) {
                for (UserRoleRel userRoleRel : userRoleRelList) {
                    // 获取用户关联角色名称
                    String roleName = roleService.find(userRoleRel.getRoleId()).getRoleName();
                    authorityList.add(new SimpleGrantedAuthority(roleName));
                }
            }
            userdetails = new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), authorityList);
        }
        return userdetails;
    }

}
